﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Z2.Core
{
	public class ParticleBasic : ObjectBase
	{

		#region Members

		private TimeSpan m_dispose;
		private TimeSpan m_anim;
		private DateTime m_animNow;
		private float m_rotation;
		private float m_rotationStep;
		private float m_visibility;
		private float m_visibilityStep;

		#endregion

		#region Constructors

		public ParticleBasic(Sprite sprite)
			: base(sprite)
		{
			Behavior = new ParticleBehavior(0.4f);
			MaxHorizontalSpeed = 8.0f;
			LiveToMax = 3000;
			LiveToMin = 1500;
			HasLight = true;
		}

		public ParticleBasic(string asset)
			: base(SpriteManager.Instance.LoadSprite(asset, 1, 1, "particles"))
		{
			Behavior =  new ParticleBehavior(0.4f);
			MaxHorizontalSpeed = 8.0f;
			Light.LightSize = new Rectangle(0, 0, 32, 32);
			Sprite.Depth = Depths.Particle;
			LiveToMax = 3000;
			LiveToMin = 1500;
			HasLight = true;
		}

		#endregion

		#region Events

		public event EventHandler Delete;

		#endregion

		public int LiveToMin { get; set; }
		public int LiveToMax { get; set; }
		public bool HasLight { get; set; }

		public bool IgnoresObjects { get; set; }

		#region Methods

		public override void Initialize()
		{
			base.Initialize();
			
			NormalizeVectorTime = 100;

			m_visibility = 1.0f;
			m_rotation = ((float)RandomGenerator.Random.Next(0, 50)) / 100.0f;
			
			m_rotationStep = m_rotation / 10.0f;
			m_visibilityStep = m_visibility / 10.0f;

			if (m_move.X < 0)
			{
				m_rotation = -m_rotation;
				m_rotationStep = -m_rotationStep;
			}

			m_dispose = new TimeSpan(0, 0, 0, 0, RandomGenerator.Random.Next(this.LiveToMin, this.LiveToMax));
			m_anim = new TimeSpan(0, 0, 0, 0, (int)m_dispose.TotalMilliseconds / 10);
			m_animNow = DateTime.Now;

			Sprite.StartAnimation();
		}

		protected override void ModifyVector()
		{
			base.ModifyVector();
			
			Sprite.Rotate(Move.X/5.0f);
		}

		public override void Update()
		{
			base.Update();
			
			if (DateTime.Now.Subtract(m_animNow) > m_anim)
			{
				m_animNow = DateTime.Now;
				Sprite.Visibility -= m_visibilityStep;
			}

			if (DateTime.Now.Subtract(Lifetime) > m_dispose)
			{
				this.Delete(this, EventArgs.Empty);
				this.Destroy();
			}
		}

		public override void DrawLight(SpriteBatch batch)
		{
			if (!HasLight) return;
			base.DrawLight(batch);
		}

		internal override bool CantCollide(ObjectBase obj)
		{
			return this.IgnoresObjects;
		}

		#endregion

	}
}
